<?php

namespace App\Services\Game\Other;

use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Game\Common\Dictionary;
use App\Exceptions\Response\ServiceException;

class DictionaryService extends Service
{
    use DatabaseMysql;

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]
     */
    public function getList($request)
    {
        $query = Dictionary::query();

        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $query);
        // 筛选【搜索】
        $this->makeWhereParamLike($request, 'keyword', $query, 'content', false);
        // 筛选【语言】
        $this->makeWhereParam($request, 'language', $query);
        // 筛选【分类】
        $this->makeWhereParam($request, 'classify', $query);

        // 数据条数
        $total = (clone $query)->count();
        // 排序分页
        $this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->get();

        return [
            $collection,
            $total
        ];
    }

    /**
     * 创建数据
     *
     * @param \Illuminate\Http\Request $request
     * @return Dictionary
     */
    public function store($request)
    {
        $data = $request->only(['content', 'language', 'classify']);

        $data['key'] = md5($data['content']);

        if (Dictionary::where('key', $data['key'])->exists()) {
            throw new ServiceException(ServiceException::SERVICE_EXISTED_DATA);
        }

        return Dictionary::Create($data);
    }
}
